<template>
	<view class="page">
		<!-- 我的钱包页面 -->
		<view v-if="currentPage === 'wallet'" class="wallet-container">
			<view class="nav-bar">
				<uni-icons @click="goBack" type="left" size="20" />
				<text class="title">我的钱包</text>
			</view>

			<scroll-view scroll-y class="content-scroll">
				<view class="balance-card">
					<view class="balance-info">
						<text class="label">当前收益</text>
						<text class="amount">¥ {{walletInfo.balance}}</text>
					</view>
					<view class="button-group">
					</view>
				</view>

				<view class="transaction-list">
					<view class="list-title">交易记录</view>
					<view v-for="(item, index) in transactions" :key="index" class="transaction-item">
						<uni-icons :type="item.type === 'income' ? 'plus' : 'minus'" size="24" />
						<view class="transaction-info">
							<text class="description">{{item.description}}</text>
							<text class="time">{{item.time}}</text>
						</view>
						<text
							:class="['amount', item.type]">{{item.type === 'income' ? '+' : '-'}}{{item.amount}}</text>
					</view>
				</view>
			</scroll-view>
		</view>

		<!-- 收藏夹页面 -->
		<view v-if="currentPage === 'favorite'" class="favorite-container">
			<view class="nav-bar">
				<uni-icons @click="goBack" type="left" size="20" />
				<text class="title">我的收藏</text>
			</view>

			<scroll-view scroll-y class="content-scroll">
				<view class="tabs">
					<text v-for="(tab, index) in tabs" :key="index"
						:class="['tab-item', { active: currentTab === index }]" @click="switchTab(index)">
						{{tab}}
					</text>
				</view>

				<view class="favorite-grid">
					<view v-for="(item, index) in favoriteItems" :key="index" class="grid-item">
						<image :src="item.image" mode="aspectFill" class="item-image" />
						<text class="item-name">{{item.name}}</text>
						<text class="item-price" v-if="item.price">¥{{item.price}}</text>
						<uni-icons type="heart-filled" size="24" color="#ff4d4f" class="favorite-icon"
							@click="cancelFavorite(index)" />
					</view>
				</view>
			</scroll-view>
		</view>

		<!-- 帮助中心页面 -->
		<view v-if="currentPage === 'help'" class="help-container">
			<view class="nav-bar">
				<uni-icons @click="goBack" type="left" size="20" />
				<text class="title">帮助中心</text>
			</view>

			<scroll-view scroll-y class="content-scroll">
				<view class="search-bar">
					<uni-icons type="search" size="20" />
					<input type="text" placeholder="搜索常见问题" v-model="searchText" />
				</view>

				<view class="faq-categories">
					<view v-for="(category, index) in faqCategories" :key="index" class="category-item"
						@click="selectCategory(index)">
						<uni-icons :type="category.icon" size="28" />
						<text>{{category.name}}</text>
					</view>
				</view>

				<view class="faq-list">
					<view v-for="(faq, index) in faqs" :key="index" class="faq-item" @click="toggleFaq(index)">
						<view class="faq-header">
							<text>{{faq.question}}</text>
							<uni-icons :type="faq.isOpen ? 'up' : 'down'" size="20" />
						</view>
						<view v-if="faq.isOpen" class="faq-answer">
							{{faq.answer}}
						</view>
					</view>
				</view>
			</scroll-view>
		</view>

		<!-- 联系客服页面 -->
		<view v-if="currentPage === 'service'" class="service-container">
			<view class="nav-bar">
				<uni-icons @click="goBack" type="left" size="20" />
				<text class="title">联系客服</text>
			</view>

			<scroll-view scroll-y class="chat-container" :scroll-top="scrollTop" :scroll-into-view="scrollToMessage">
				<view v-for="(msg, index) in messages" :key="index" class="message-item">
					<view class="time-stamp">{{msg.time}}</view>
					<view :class="['message-content', msg.type]">
						<image v-if="msg.type === 'service'"
							src="https://ai-public.mastergo.com/ai/img_res/512a47558b2536f09004012822f9a8a9.jpg"
							class="avatar" />
						<view class="message-bubble">{{msg.content}}</view>
						<image v-if="msg.type === 'user'"
							src="https://ai-public.mastergo.com/ai/img_res/b817c8453404fc646492ce9df336100f.jpg"
							class="avatar" />
					</view>
				</view>
			</scroll-view>

			<view class="input-area">
				<input type="text" v-model="inputMessage" placeholder="请输入消息..." @confirm="sendMessage" />
				<uni-icons type="image" size="24" class="function-icon" @click="uploadImage" />
				<uni-button type="primary" size="mini" @click="sendMessage">发送</uni-button>
			</view>
		</view>
	</view>
</template>

<script lang="ts" setup>
	import { ref, reactive } from 'vue';
	import { getAcceptOrderList } from '../../api/order';
	import { onLoad } from '@dcloudio/uni-app';

	// 当前页面状态
	const currentPage = ref('wallet');

	// 当前收益（自动计算）
	const walletInfo = reactive({
		balance: '0.00'
	});

	// 交易记录数组
	const transactions = ref<any[]>([]);

	// 收藏夹相关
	const tabs = ['全部', '商品', '店铺'];
	const currentTab = ref(0);
	const favoriteItems = reactive([
		{
			image: 'https://ai-public.mastergo.com/ai/img_res/ad70490fd4f3f1821bf07f0687eb4963.jpg',
			name: '智能手表',
			price: '999.00'
		},
		{
			image: 'https://ai-public.mastergo.com/ai/img_res/351798096d9445bad5af60429054646a.jpg',
			name: '时尚外套',
			price: '299.00'
		}
	]);

	// 帮助中心相关
	const faqCategories = reactive([
		{ name: '账户相关', icon: 'person' },
		{ name: '订单相关', icon: 'cart' },
		{ name: '支付相关', icon: 'wallet' }
	]);
	const faqs = reactive([
		{
			question: '如何修改账户密码？',
			answer: '进入个人中心-账户设置-密码修改，按提示操作即可完成密码修改。',
			isOpen: false
		},
		{
			question: '订单何时发货？',
			answer: '正常情况下订单会在24小时内发货，特殊情况会有客服与您联系。',
			isOpen: false
		}
	]);

	// 客服聊天相关
	const messages = reactive([
		{ type: 'service', content: '您好，很高兴为您服务！', time: '14:30' },
		{ type: 'user', content: '你好，我想咨询一个问题', time: '14:31' }
	]);
	const searchText = ref('');
	const inputMessage = ref('');
	const scrollTop = ref(0);
	const scrollToMessage = ref('');

	// 返回上一级
	const goBack = () => {
		uni.navigateBack(1)
	};

	// 模拟充值/提现
	const handleRecharge = () => {
		uni.showToast({
			icon: "success",
			title: '暂未开发'
		})
	};
	const handleWithdraw = () => {
		uni.showToast({
			icon: 'fail',
			title: '暂未开发'
		})
	};

	// 收藏夹操作
	const switchTab = (index : number) => {
		currentTab.value = index;
	};
	const cancelFavorite = (index : number) => { };
	const selectCategory = (index : number) => { };
	const toggleFaq = (index : number) => {
		faqs[index].isOpen = !faqs[index].isOpen;
	};

	// 发送消息
	const sendMessage = () => {
		if (!inputMessage.value.trim()) return;

		messages.push({
			type: 'user',
			content: inputMessage.value,
			time: new Date().toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
		});
		inputMessage.value = '';
		scrollToBottom();
	};

	// 滚动到底部
	const scrollToBottom = () => {
		scrollTop.value = 9999;
	};
	const uploadImage = () => { };

	// 格式化时间
	const formatDate = (isoString : string) : string => {
		const date = new Date(isoString);
		const y = date.getFullYear();
		const m = String(date.getMonth() + 1).padStart(2, '0');
		const d = String(date.getDate()).padStart(2, '0');
		const h = String(date.getHours()).padStart(2, '0');
		const min = String(date.getMinutes()).padStart(2, '0');
		return `${y}-${m}-${d} ${h}:${min}`;
	};

	// 获取订单并映射为交易记录
	const fetOrderList = async () => {
		const res = await getAcceptOrderList();
		if (res.code === 200) {
			const rawOrders = res.data;

			// 去重（按 orderId）
			const seen = new Set();
			const uniqueOrders = rawOrders.filter(order => {
				if (seen.has(order.orderId)) return false;
				seen.add(order.orderId);
				return true;
			});

			// 映射为交易记录
			transactions.value = uniqueOrders.map(order => ({
				type: 'income',
				description: `订单号：${order.orderId}`,
				time: formatDate(order.orderTime),
				amount: Number(order.fee).toFixed(2)
			}));

			// 汇总费用
			const total = uniqueOrders.reduce((sum, order) => sum + Number(order.fee), 0);
			walletInfo.balance = total.toFixed(2);
		}
	};

	// 页面加载时获取订单
	onLoad(() => {
		fetOrderList();
	});
</script>


<style>
	page {
		height: 100%;
	}

	.page {
		height: 100%;
		background-color: #f5f5f5;
	}

	.nav-bar {
		display: flex;
		align-items: center;
		height: 88rpx;
		padding: 0 30rpx;
		background-color: #ffffff;
		border-bottom: 1px solid #eee;
	}

	.nav-bar .title {
		margin-left: 30rpx;
		font-size: 16px;
		font-weight: 500;
	}

	.content-scroll {
		height: calc(100% - 88rpx);
		overflow: auto;
	}

	/* 钱包页面样式 */
	.balance-card {
		margin: 30rpx;
		padding: 40rpx;
		background-color: #ffffff;
		border-radius: 12px;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
	}

	.balance-info {
		margin-bottom: 40rpx;
	}

	.balance-info .label {
		font-size: 14px;
		color: #666;
	}

	.balance-info .amount {
		display: block;
		margin-top: 20rpx;
		font-size: 32px;
		font-weight: 600;
		color: #333;
	}

	.button-group {
		display: flex;
		gap: 20rpx;
	}

	.transaction-list {
		margin: 30rpx;
		padding: 30rpx;
		background-color: #ffffff;
		border-radius: 12px;
	}

	.list-title {
		margin-bottom: 30rpx;
		font-size: 16px;
		font-weight: 500;
	}

	.transaction-item {
		display: flex;
		align-items: center;
		padding: 20rpx 0;
		border-bottom: 1px solid #eee;
	}

	.transaction-info {
		flex: 1;
		margin-left: 20rpx;
	}

	.transaction-info .description {
		font-size: 14px;
		color: #333;
	}

	.transaction-info .time {
		display: block;
		margin-top: 10rpx;
		font-size: 12px;
		color: #999;
	}

	.transaction-item .amount {
		font-size: 16px;
		font-weight: 500;
	}

	.transaction-item .amount.income {
		color: #52c41a;
	}

	.transaction-item .amount.expense {
		color: #ff4d4f;
	}

	/* 收藏夹页面样式 */
	.tabs {
		display: flex;
		padding: 20rpx 30rpx;
		background-color: #ffffff;
	}

	.tab-item {
		padding: 20rpx 40rpx;
		font-size: 14px;
		color: #666;
		border-radius: 20px;
	}

	.tab-item.active {
		color: #1890ff;
		background-color: #e6f7ff;
	}

	.favorite-grid {
		display: grid;
		grid-template-columns: repeat(2, 1fr);
		gap: 20rpx;
		padding: 30rpx;
	}

	.grid-item {
		position: relative;
		background-color: #ffffff;
		border-radius: 12px;
		overflow: hidden;
	}

	.item-image {
		width: 100%;
		height: 300rpx;
		object-fit: cover;
	}

	.item-name {
		display: block;
		padding: 20rpx;
		font-size: 14px;
		color: #333;
	}

	.item-price {
		display: block;
		padding: 0 20rpx 20rpx;
		font-size: 16px;
		color: #ff4d4f;
		font-weight: 500;
	}

	.favorite-icon {
		position: absolute;
		top: 20rpx;
		right: 20rpx;
	}

	/* 帮助中心页面样式 */
	.search-bar {
		display: flex;
		align-items: center;
		margin: 30rpx;
		padding: 20rpx;
		background-color: #ffffff;
		border-radius: 8px;
	}

	.search-bar input {
		flex: 1;
		margin-left: 20rpx;
		font-size: 14px;
	}

	.faq-categories {
		display: grid;
		grid-template-columns: repeat(3, 1fr);
		gap: 20rpx;
		padding: 30rpx;
	}

	.category-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 30rpx;
		background-color: #ffffff;
		border-radius: 12px;
	}

	.category-item text {
		margin-top: 20rpx;
		font-size: 14px;
		color: #333;
	}

	.faq-list {
		margin: 30rpx;
	}

	.faq-item {
		margin-bottom: 20rpx;
		background-color: #ffffff;
		border-radius: 12px;
		overflow: hidden;
	}

	.faq-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 30rpx;
	}

	.faq-header text {
		font-size: 14px;
		color: #333;
	}

	.faq-answer {
		padding: 30rpx;
		font-size: 14px;
		color: #666;
		background-color: #f9f9f9;
	}

	/* 客服页面样式 */
	.service-container {
		display: flex;
		flex-direction: column;
		height: 100%;
	}

	.chat-container {
		flex: 1;
		padding: 30rpx;
		overflow: auto;
	}

	.message-item {
		margin-bottom: 30rpx;
	}

	.time-stamp {
		text-align: center;
		margin-bottom: 20rpx;
		font-size: 12px;
		color: #999;
	}

	.message-content {
		display: flex;
		align-items: flex-start;
		margin-bottom: 20rpx;
	}

	.message-content.service {
		flex-direction: row;
	}

	.message-content.user {
		flex-direction: row-reverse;
	}

	.avatar {
		width: 80rpx;
		height: 80rpx;
		border-radius: 50%;
	}

	.message-bubble {
		max-width: 70%;
		margin: 0 20rpx;
		padding: 20rpx;
		font-size: 14px;
		border-radius: 12px;
	}

	.service .message-bubble {
		background-color: #ffffff;
		color: #333;
	}

	.user .message-bubble {
		background-color: #1890ff;
		color: #ffffff;
	}

	.input-area {
		display: flex;
		align-items: center;
		padding: 20rpx 30rpx;
		background-color: #ffffff;
		border-top: 1px solid #eee;
	}

	.input-area input {
		flex: 1;
		margin-right: 20rpx;
		padding: 20rpx;
		font-size: 14px;
		background-color: #f5f5f5;
		border-radius: 8px;
	}

	.function-icon {
		margin-right: 20rpx;
	}
</style>